var getms = function (time) {
  let h =
    (time.getHours() < 10 ? '0' + time.getHours() : time.getHours()) + ':';
  let m =
    (time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes()) + '';
  let timing = h + m;
  return timing;
};

const getTime = (time, done) => {
  let M =
    (time.getMonth() + 1 < 10
      ? '0' + (time.getMonth() + 1)
      : time.getMonth() + 1) + '-';
  let D = time.getDate() + ' ';
  let h =
    (time.getHours() < 10 ? '0' + time.getHours() : time.getHours()) + ':';
  let m =
    (time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes()) + '';
  let s = time.getSeconds();
  let timing = M + D;
  if (done) {
    return timing;
  } else {
    return M + D + h + m;
  }
};

function getTimeS(timestamp, timdone) {
  // 当前时间
  var currentDate = new Date();
  // 目标判断时间
  var srcDate = new Date(parseInt(timestamp));
  var currentYear = currentDate.getFullYear();
  var currentMonth = currentDate.getMonth() + 1;
  var currentDateD = currentDate.getDate();

  var srcYear = srcDate.getFullYear();
  var srcMonth = srcDate.getMonth() + 1;
  var srcDateD = srcDate.getDate();

  var ret = '';
  var timetoStr = timdone ? ' ' + getms(srcDate) : '';
  // 今年
  if (currentYear == srcYear) {
    var currentTimestamp = currentDate.getTime();
    var srcTimestamp = timestamp;
    // 相差时间（单位：毫秒）
    var deltaTime = currentTimestamp - srcTimestamp;
    // 当天（月份和日期一致才是）
    if (currentMonth == srcMonth && currentDateD == srcDateD) {
      // 时间相差60秒以内
      if (deltaTime < 60 * 1000) ret = '刚刚';
      // 否则当天其它时间段的，直接显示“时:分”的形式
      else ret = getms(srcDate);
    }
    // 当年 && 当天之外的时间（即昨天及以前的时间）
    else {
      // 昨天（以“现在”的时候为基准-1天）
      var yesterdayDate = new Date();
      yesterdayDate.setDate(yesterdayDate.getDate() - 1);
      // 前天（以“现在”的时候为基准-2天）
      var beforeYesterdayDate = new Date();
      beforeYesterdayDate.setDate(beforeYesterdayDate.getDate() - 2);
      if (
        srcMonth == yesterdayDate.getMonth() + 1 &&
        srcDateD == yesterdayDate.getDate()
      )
        ret = '昨天' + timetoStr; // -1d
      else if (
        srcMonth == beforeYesterdayDate.getMonth() + 1 &&
        srcDateD == beforeYesterdayDate.getDate()
      )
        ret = '前天' + timetoStr; // -2d
      else {
        // 跟当前时间相差的小时数
        var deltaHour = deltaTime / (3600 * 1000);
        // 如果小于或等 7*24小时就显示星期几
        if (deltaHour <= 7 * 24) {
          var weekday = new Array(7);
          weekday[0] = '星期日';
          weekday[1] = '星期一';
          weekday[2] = '星期二';
          weekday[3] = '星期三';
          weekday[4] = '星期四';
          weekday[5] = '星期五';
          weekday[6] = '星期六';
          // 取出当前是星期几
          var weedayDesc = weekday[srcDate.getDay()];
          ret = weedayDesc + timetoStr;
        }
        // 否则直接显示完整日期时间
        else ret = getTime(srcDate, true) + timetoStr;
      }
    }
  } else {
    ret = getTime(srcDate, false);
  }
  return ret;
}

export default getTimeS;
